package io.wit.modules.wit.controller;

import io.wit.common.utils.PageUtils;
import io.wit.common.utils.Query;
import io.wit.common.utils.R;
import io.wit.config.ConfigFile;
import io.wit.modules.sys.controller.AbstractController;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.modules.wit.entity.FarmEntity;
import io.wit.modules.wit.service.FarmService;
import io.wit.tool.ToolClient;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 基地管理
*/
@RestController
@RequestMapping("farm")
public class FarmController extends AbstractController{

    @Autowired
	private FarmService farmService;

    @Value("${role_value2}")
    private Long roleValue2;

    @Value("${manager_agent_role}")
    private String manager_agent_role;

    @Value("${register_dafualt_role}")
    private Long dafualtRole;

    @Value("${role_value2}")
    private long value2;

	/**
	 * 列表
	*/
	@RequestMapping("/list")
	@RequiresPermissions("farm:list")
	public R list(@RequestParam Map<String, Object> params){
        final Query query = new Query(params);
        final String username = getUserName();
        final Long roleId = getRoleId();
        if(username.equals(ConfigFile.KEY_SUPER) || roleId == value2){
            final List<FarmEntity> farmList = farmService.queryList(query);
            int total = farmService.queryTotal(query);
            final PageUtils pageUtil = new PageUtils(farmList, total, query.getLimit(), query.getPage());
            return R.ok().put("page", pageUtil);
        }else{
            final Integer options = getOptions();
            if(options == 2 || options == 3){}else{
                final Long subjectId = getSubjectId();
                if(subjectId != null){
                    query.put("subjectId",subjectId);
                }else{
                    final PageUtils page = new PageUtils(new ArrayList<>(),0,query.getLimit(), query.getPage());
                    return R.ok().put("page",page).put("msg","当前账号尚未添加经营主体");
                }
            }
            final List<FarmEntity> farmList = farmService.queryList(query);
            final int total = farmService.queryTotal(query);
            final PageUtils pageUtil = new PageUtils(farmList, total, query.getLimit(), query.getPage());
            return R.ok().put("page", pageUtil);
        }
	}

	/**
	 * 信息
	 */
	@GetMapping("/info/{farmId}")
	@RequiresPermissions("farm:info")
	public void info(@PathVariable("farmId") Long farmId,final HttpServletResponse response){
        final String json = farmService.queryMap(farmId);
        ToolClient.responseJson(json,response);
	}

    /**基地类型*/
	@GetMapping("/getTypeArea")
    public void getTypeArea(final HttpServletResponse response){
        final String json = farmService.getTypeArea();
        ToolClient.responseJson(json,response);
    }

    /**销售方式*/
	@GetMapping("/getTypeSales")
    public void getTypeSales(final HttpServletResponse response){
        final String json = farmService.getTypeSales();
        ToolClient.responseJson(json,response);
    }

    /**种养类型*/
    @GetMapping("/getTypePlant")
    public void getTypePlant(final HttpServletResponse response){
        final String json = farmService.getTypePlant();
        ToolClient.responseJson(json,response);
    }

    /**单位*/
    @GetMapping("/getTypeUnit")
    public void getTypeUnit(final HttpServletResponse response){
        final String json = farmService.getTypeUnit();
        ToolClient.responseJson(json,response);
    }
	
	/**
	 * 保存
	*/
	@RequestMapping("/save")
	@RequiresPermissions("farm:save")
	public void save(final HttpServletRequest request,final HttpServletResponse response){
        final Long roleId = getRoleId();
        if(roleId == value2 || roleId == -1){
            final String json = ToolClient.createJsonFail("无权限操作");
            ToolClient.responseJson(json,response);
        }else{
            final String json = farmService.save(request);
            ToolClient.responseJson(json,response);
        }
	}
	
	/**
	 * 修改
	*/
	@PostMapping("/update")
	@RequiresPermissions("farm:update")
    public void update(final HttpServletRequest request,final HttpServletResponse response){
        final Long roleId = getRoleId();
        if(roleId == value2 || roleId == -1){
            final String json = ToolClient.createJsonFail("无权限操作");
            ToolClient.responseJson(json,response);
        }else{
            final String json = farmService.update(request);
            ToolClient.responseJson(json,response);
        }
    }
	
	/**
	 * 删除
	*/
	@RequestMapping("/delete")
	@RequiresPermissions("farm:delete")
	public R delete(@RequestBody Long[] farmIds){
		farmService.deleteBatch(farmIds);
		return R.ok();
	}

	@GetMapping("/getSelect")
	public R getSelect(Long subjectId) {
		List<FarmEntity> farmList = farmService.farmList(subjectId);
		return R.ok().put("itemList", farmList);
	}

	@GetMapping("/getAllFarm")
	public void getAllFarm(final HttpServletResponse response) {
	    try {
            final Map<String, Object> query = new HashMap<String,Object>();
            final SysUserEntity user = ShiroUtils.getUserEntity();
            final String username = user.getUsername();
            final Long subjectId = user.getSubjectId();
            if(username.equals(ConfigFile.KEY_SUPER)){//admin或平台运维人员
                final String json = ToolClient.queryJson(farmService.mapDashboard(query));
                ToolClient.responseJson(json,response);
                return;
            }
            if(subjectId == null){
                ToolClient.responseJson(ToolClient.createJsonFail("经营主体为空"),response);
                return;
            }
            final Integer userType = user.getUserType();
            if(userType == 2){//员工
                query.put("subjectId",subjectId);
                final String json = ToolClient.queryJson(farmService.mapDashboard(query));
                ToolClient.responseJson(json,response);
                return;
            }else{
                final Long roleId = user.getRoleId();
                if(roleId.equals(roleValue2)){//admin或平台运维人员
                    final String json = ToolClient.queryJson(farmService.mapDashboard(query));
                    ToolClient.responseJson(json,response);
                    return;
                }
                if(roleId.equals(dafualtRole)){//经营主体
                    query.put("subjectId",subjectId);
                    final String json = ToolClient.queryJson(farmService.mapDashboard(query));
                    ToolClient.responseJson(json,response);
                    return;
                }
                //代理商或政府管理部门
                final String[] arrays = manager_agent_role.split(",");
                boolean bl = false;
                for(int x = 0; x < arrays.length; x++){
                    final String array = arrays[x];
                    final long value = Long.parseLong(array);
                    if(roleId == value){
                        bl = true;
                        break;
                    }
                }
                if(bl){
                    final Integer options = user.getOptions();
                    if(options == 2 || options == 3){//是否是代理或管理部门
                        final String areas = user.getAreaIds();
                        if(areas != null){
                            final List<Long> listArea = new ArrayList<>();
                            final String[] arrs = areas.split(",");
                            for(int x = 0; x < arrs.length; x++){
                                listArea.add(Long.parseLong(arrs[x]));
                            }
                            if(listArea.size()>0){
                                query.put("listArea",listArea);
                            }
                        }
                    }
                    final List<Map<String,Object>> proxyAreas = farmService.getProxyArea(query);//获取代理区域或政府管理部门区域数据
                    ToolClient.responseJson(ToolClient.queryJson(proxyAreas),response);
                }else {
                    ToolClient.responseJson(ToolClient.unauthorized(),response);
                }
            }
	    } catch (final Exception e) {
            final String json = ToolClient.invalidToken();
            ToolClient.responseJson(json,response);
	    }
	}
}